package com.pactera.madp.cp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.WorkContactEmployeeEntity;
import com.pactera.madp.cp.api.entity.daily.WorkContactDailyEntity;
import com.pactera.madp.cp.api.entity.daily.WorkDailySendEntity;
import com.pactera.madp.cp.api.model.workcontact.WorkContactDailyIndexResp;
import com.pactera.madp.cp.api.model.workcontact.WorkContactDailyResp;
import com.pactera.madp.cp.api.util.Day;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.daily.WorkContactDailyMapper;
import com.pactera.madp.cp.service.IWorkContactDailyService;
import com.pactera.madp.cp.service.IWorkContactEmployeeService;
import com.pactera.madp.cp.service.IWorkDailySendService;
import com.pactera.madp.cp.service.TakeOverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static java.util.Comparator.comparing;

@Service
public class WorkContactDailyServiceImpl extends ServiceImpl<WorkContactDailyMapper, WorkContactDailyEntity> implements IWorkContactDailyService {

    @Resource
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private IWorkDailySendService workDailySendService;
    @Autowired
    private TakeOverService takeOverService;

    @Override
    public WorkContactDailyIndexResp contactDailyGenerate(Integer corpId, Integer dailyType, Day day) {
        LocalDate date;
        if (dailyType == 2) {
            date = day.getFirstDayOfWeek();
        } else if (dailyType == 3) {
            date = day.getFirstDayOfMonth();
        } else {
            date = LocalDate.now();
        }
        // 判断首次生成情况
        if (getNew(dailyType, corpId)) {
            WorkContactDailyIndexResp first = getFirst(corpId, dailyType, date);
            return first;
        }
        // =====================================================> 统计
        //每日净增客戶
        Integer realAddNum;
        //每日变换客戶數
        Integer changeNum;
        //客户增加数
        Integer addContact;
        //前一天的日报
        WorkContactDailyEntity entity = this.getOne(Wrappers.<WorkContactDailyEntity>lambdaQuery()
                .eq(WorkContactDailyEntity::getCorpId, corpId)
                .orderByDesc(WorkContactDailyEntity::getCreateTime)
                .eq(WorkContactDailyEntity::getDailyType, dailyType)
                .last("limit 1"));

        WorkContactDailyIndexResp workContactDailyIndexResp = new WorkContactDailyIndexResp();

        //今天的记录情况
        WorkContactDailyEntity nowCondition = getNowCondition(corpId, dailyType, date);
        //改变量
        changeNum = nowCondition.getTotalContact() - entity.getTotalContact();
        //增加量
        addContact = nowCondition.getTotalRecord() - entity.getTotalRecord();
        //净增量
        realAddNum = nowCondition.getRealRecord() - entity.getRealRecord();

        nowCondition.setChangeContact(changeNum);
        nowCondition.setRealAddContact(realAddNum);
        nowCondition.setAddContact(addContact);

        nowCondition.setCorpId(corpId);
        nowCondition.setDailyType(dailyType);
        nowCondition.setCreateDay(date);
        nowCondition.setCreateTime(LocalDateTime.now());
        this.save(nowCondition);

        //封装进返回对象中
        workContactDailyIndexResp.setTime(date.toString());
        workContactDailyIndexResp.setTotal(nowCondition.getTotalContact());
        workContactDailyIndexResp.setAddNum(changeNum);
        workContactDailyIndexResp.setRealAddNum(realAddNum);
        workContactDailyIndexResp.setLoss(nowCondition.getAddContact() - changeNum);
        return workContactDailyIndexResp;
    }

    //获取今天的客户日报数据
    WorkContactDailyEntity getNowCondition(Integer corpId, Integer type, LocalDate date) {
        //每日客戶總數
        Integer total;
        //记录总数
        Integer totalRecord;
        //不重复记录数
        Integer realRecord;

        //求出今天的客户总数
        total = workContactEmployeeService.lambdaQuery()
               .eq(WorkContactEmployeeEntity::getCorpId, corpId)
               .count();
        totalRecord = workContactEmployeeService.getRecord(corpId);
        //求出不重复记录数
        realRecord = workContactEmployeeService.getReal(corpId);

        WorkContactDailyEntity workContactDailyEntity = new WorkContactDailyEntity();
        //Integer takeOverCount = takeOverService.getTakeOverCount(corpId, date, type);
        workContactDailyEntity.setRealRecord(realRecord);
        workContactDailyEntity.setTotalContact(total);
        workContactDailyEntity.setTotalRecord(totalRecord);
        return workContactDailyEntity;
    }
    @Override
    public WorkContactDailyResp dailyQuery(String endDate, Integer dailyType) {
        Integer corpId = CorpContextHolder.getCorpId1();
        Day day = new Day(Calendar.getInstance());
        LocalDate date;
        if (dailyType == 2) {
            date = day.getFirstDayOfWeek();
        } else if (dailyType == 3) {
            date = day.getFirstDayOfMonth();
        } else {
            date = LocalDate.now();
        }
        List<WorkContactDailyEntity> list = this.lambdaQuery()
                .eq(WorkContactDailyEntity::getCorpId, corpId)
                .eq(WorkContactDailyEntity::getDailyType, dailyType)
                .le(WorkContactDailyEntity::getCreateDay, date)
                .orderByDesc(WorkContactDailyEntity::getCreateTime)
                .last("limit 7")
                .list();
        ArrayList<WorkContactDailyIndexResp> workContactDailyIndexResps = new ArrayList<>();
        Iterator<WorkContactDailyEntity> iterator = list.iterator();
        while (iterator.hasNext()){
            WorkContactDailyEntity next = iterator.next();
            WorkContactDailyIndexResp workContactDailyIndexResp = new WorkContactDailyIndexResp();

            workContactDailyIndexResp.setTime(next.getCreateDay().toString());
            workContactDailyIndexResp.setLoss(next.getAddContact() - next.getChangeContact());
            workContactDailyIndexResp.setRealAddNum(next.getRealAddContact());
            workContactDailyIndexResp.setAddNum(next.getChangeContact());
            workContactDailyIndexResp.setTotal(next.getTotalContact());
            workContactDailyIndexResps.add(workContactDailyIndexResp);
        }
        workContactDailyIndexResps.sort(comparing(WorkContactDailyIndexResp::getTime).reversed());

        WorkContactDailyEntity entity = this.getOne(Wrappers.<WorkContactDailyEntity>lambdaQuery()
                .eq(WorkContactDailyEntity::getCorpId, corpId)
                .eq(WorkContactDailyEntity::getDailyType, dailyType)
                .orderByDesc(WorkContactDailyEntity::getCreateTime)
                .last("limit 1"));
        WorkContactDailyResp workContactDailyResp = new WorkContactDailyResp();
        Integer lossContact = 0;
        Integer addContact = 0;
        Integer totalContact = 0;
        Integer realAddContact = 0;
        workContactDailyResp.setTime(entity.getCreateDay().toString());
        lossContact = entity.getAddContact() - entity.getChangeContact();
        addContact = entity.getChangeContact();
        totalContact = entity.getTotalContact();
        realAddContact = entity.getAddContact();


        workContactDailyResp.setLoss(lossContact);
        workContactDailyResp.setAddNum(addContact);
        workContactDailyResp.setTotal(totalContact);
        workContactDailyResp.setRealAddNum(realAddContact);
        workContactDailyResp.setList(workContactDailyIndexResps);
        WorkDailySendEntity one = workDailySendService.getOne(Wrappers.<WorkDailySendEntity>query().eq("corp_id", corpId));
        if (Objects.isNull(one)) return null;
        List<String> contact = getContactList(one);
        workContactDailyResp.setContact(contact);

        return workContactDailyResp;
    }

     //判定是否初次使用
    Boolean getNew(Integer dailyType,Integer corpId){
        int size = this.lambdaQuery()
                .eq(WorkContactDailyEntity::getDailyType, dailyType).eq(WorkContactDailyEntity::getCorpId, corpId).count();
        return size == 0? true: false;
    }
    //初次使用统计
    WorkContactDailyIndexResp getFirst(Integer corpId, Integer dailyType, LocalDate date){
        //每日客戶總數
        Integer total;
        //记录总数
        Integer totalRecord;
        //记录不重复总数
        Integer realTotalRecord;
        //客户增长数
        Integer addContact;
        //客户净增数
        Integer realAddContact;
        //客户净增数
        Integer changeContact;

        totalRecord = workContactEmployeeService.getRecord(corpId);
        total = workContactEmployeeService.lambdaQuery().eq(WorkContactEmployeeEntity::getCorpId, corpId).count();
        realTotalRecord = workContactEmployeeService.getReal(corpId);

        addContact = totalRecord;
        realAddContact = realTotalRecord;
        changeContact = total;

        WorkContactDailyEntity workContactDailyEntity = new WorkContactDailyEntity();

        workContactDailyEntity.setChangeContact(changeContact);
        workContactDailyEntity.setRealAddContact(realAddContact);
        workContactDailyEntity.setAddContact(addContact);

        workContactDailyEntity.setTotalContact(total);
        workContactDailyEntity.setRealRecord(realTotalRecord);
        workContactDailyEntity.setTotalRecord(totalRecord);

        workContactDailyEntity.setCreateDay(date);
        workContactDailyEntity.setCorpId(corpId);
        workContactDailyEntity.setDailyType(dailyType);
        workContactDailyEntity.setCreateTime(LocalDateTime.now());
        this.save(workContactDailyEntity);
        WorkContactDailyIndexResp workContactDailyIndexResp = new WorkContactDailyIndexResp();

        workContactDailyIndexResp.setTotal(total);
        workContactDailyIndexResp.setAddNum(total);
        workContactDailyIndexResp.setRealAddNum(realAddContact);
        workContactDailyIndexResp.setLoss(totalRecord - total);

        workContactDailyIndexResp.setTime(date.toString());
        return workContactDailyIndexResp;
    }
    List<String> getContactList(WorkDailySendEntity entity) {
        ArrayList<String> list = new ArrayList<>();
        if (entity.isContactTotalContact()) list.add("total");
        if (entity.isContactRealAddContact()) list.add("realAddNum");
        if (entity.isContactChangeContact()) list.add("addNum");
        if (entity.isContactLossContact()) list.add("loss");

        return list;
    }
}

